//
//  ChatKeyboardView.swift
//  FY-JetChat
//
//  Created by iOS.Jet on 2019/11/14.
//  Copyright © 2019 Jett. All rights reserved.
//

import UIKit


protocol ChatKeyboardViewDelegate: AnyObject {
    /// 输入完消息
    func keyboard(_ keyboard: ChatKeyboardView, DidFinish content: String)
    /// 键盘的y值
    func keyboard(_ keyboard: ChatKeyboardView, DidObserver offsetY: CGFloat)
}

extension ChatKeyboardViewDelegate {
    func keyboard(_ keyboard: ChatKeyboardView, DidFinish content: String) {}
    func keyboard(_ keyboard: ChatKeyboardView, DidObserver offsetY: CGFloat) {}
}

class ChatKeyboardView: UIView {
    
    private let kSpace: CGFloat = 8.0
    private let kViewWH: CGFloat = 36.0
        
    weak var delegate: ChatKeyboardViewDelegate?
    fileprivate var toolBarHeight: CGFloat = 52.0
    fileprivate var lastTextHeight: CGFloat = 34.0
    fileprivate var keyboardHeight: CGFloat = 0.0
    
    /// 是否弹出了系统键盘
    fileprivate var isShowKeyboard = false
    
    /// 文本输入框
    lazy var chatTextView: ChatGrowingTextView = {
        let w: CGFloat = SCREENWIDTH - self.kSpace * 2
        let textView = ChatGrowingTextView(frame: CGRect(x: self.kSpace, y: self.kSpace, width: w, height: self.kViewWH))
        textView.placeholder = "input something..."
        textView.maxNumberOfLines = 5
        textView.delegate = self
        textView.didTextChangedHeightClosure = { [weak self] height in
            self?.changeKeyboardHeight(height: height)
        }
        return textView
    }()

    fileprivate lazy var toolBarView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: SCREENWIDTH, height: self.toolBarHeight))
        view.backgroundColor = UIColor.white
        return view
    }()
    
    // MARK: - life cycle
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupKeyboardView()
        registerNotification()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupKeyboardView()
        registerNotification()
    }
    
    func setupKeyboardView() {
        self.isUserInteractionEnabled = true
        addSubview(toolBarView)
        toolBarView.addSubview(chatTextView)
    }
    
    // MARK: - 监听键盘通知
    private func registerNotification() {
        // 监听键盘弹出通知
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame),
                                               name:UIResponder.keyboardWillChangeFrameNotification,object: nil)

        // 主要是为了获取点击空白处回收键盘的处理
        NotificationCenter.default.addObserver(self,selector: #selector(keyboardNeedHide),
                                               name: .kChatTextKeyboardNeedHide, object: nil)

    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
        print("remove --  ChatKeyboardView")
    }
}

// MARK: - UITextViewDelegate

extension ChatKeyboardView: UITextViewDelegate {
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        // 发送键&回车键处理
        if (text == "\n") {
            if (isShowKeyboard) {
                isShowKeyboard = true
            }
            sendChatMessage()
            return false
        }
        return true
    }
    
    /// 发送消息内容
    private func sendChatMessage() {
        delegate?.keyboard(self, DidFinish: self.chatTextView.text ?? "")
        changeKeyboardHeight(height: lastTextHeight)
        chatTextView.text = ""
        chatTextView.resignFirstResponder()
    }
}


// MARK: - KeyBoard Manager

extension ChatKeyboardView {

    @objc func keyboardWillChangeFrame(_ noti: NSNotification) {
        guard let userInfo = noti.userInfo else {
            return
        }
        let duration = userInfo["UIKeyboardAnimationDurationUserInfoKey"] as! Double
        let endFrame = (userInfo["UIKeyboardFrameEndUserInfoKey"] as! NSValue).cgRectValue
        let y = endFrame.origin.y
        // 获取键盘的高度
        keyboardHeight = endFrame.height
//        print("y的值是 -- \(y)")
        // 键盘弹出状态
        isShowKeyboard = true
        let option = userInfo["UIKeyboardAnimationCurveUserInfoKey"] as! Int
        let changedY = y == SCREENHEIGHT ? y:y - self.toolBarHeight
        UIView.animate(withDuration: duration, delay: 0, options: UIView.AnimationOptions(rawValue: UIView.AnimationOptions.RawValue(option)), animations: {
            self.frame = CGRect(x: 0, y: changedY, width: SCREENWIDTH, height: self.toolBarHeight)
        }, completion: nil)
    }
    
    @objc func keyboardNeedHide(_ noti: NSNotification) {
        chatTextView.resignFirstResponder()
        restToolbarContentHeight()
    }
}

// MARK: - Action

extension ChatKeyboardView {
    /// 更改容器高度
    func restToolbarContentHeight() {
        UIView.animate(withDuration: 0.25, delay: 0, options: .curveEaseOut, animations: {
            self.frame = CGRect(x: 0, y: SCREENHEIGHT, width: SCREENWIDTH, height: self.toolBarHeight)
        }, completion: nil)
        self.layoutIfNeeded()
    }
}

// MARK: - 改变输入框高度位置

extension ChatKeyboardView {
    
    func changeKeyboardHeight(_ isClear: Bool = false, height: CGFloat) {
        let textHeight = height
        toolBarHeight = textHeight + kSpace * 2
        toolBarView.frame = CGRect(x: toolBarView.mj_x, y: 0, width: toolBarView.width, height: toolBarHeight)
        chatTextView.frame = CGRect(x: chatTextView.mj_x, y: chatTextView.mj_x, width: chatTextView.width, height: textHeight)
        if (isShowKeyboard) {
            let changedY = SCREENHEIGHT - keyboardHeight - toolBarHeight
            self.frame = CGRect(x: 0, y: changedY, width: SCREENWIDTH, height: toolBarView.height)
        }else {
            let changedY = SCREENHEIGHT - toolBarView.height
            self.frame = CGRect(x: 0, y: changedY, width: SCREENWIDTH, height: toolBarView.height)
        }
        self.setNeedsLayout()
//        print("self y === \(self.frame.origin.y)")
    }
}


